package com.example.demo.exception;

import com.alibaba.fastjson.JSONObject;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Administrator
 * @className wuyp
 * @description:
 * @Date 2022/3/25 11:55
 **/
@ControllerAdvice
public class GlobalExceptionHandler {
    public static final String DEFAULT_ERROR_VIEW = "error"; // 错误显示页error.html

    /**
     * 出现异常会执行此方法
       *
      * @param request
       * @param e
       * @return
       */
     @ExceptionHandler(Exception.class)
     public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) {
                 // 设置跳转路径
                 ModelAndView mav = new ModelAndView(GlobalExceptionHandler.DEFAULT_ERROR_VIEW);
                 // 保存异常信息
                 mav.addObject("exception", e);
                 System.out.println(e.getMessage());
                // 获取请求的路径
                 mav.addObject("url", request.getRequestURL());
                 return mav;
             }
  /*  @ResponseBody
    @ExceptionHandler(Exception.class)
    public String handleException(Exception e, HttpServletRequest request,Model model) {
        String msg = e.getMessage();
        if (msg == null || msg.equals("")) {
            msg = "服务器出错";
        }
        System.out.println("--------------msg-------------"+msg);
        ModelAndView modelAndView =new ModelAndView();
        model.addAttribute("url",request.getRequestURL());
        model.addAttribute("exception",e);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 1000);
        jsonObject.put("message", msg);
        return "error";
    }*/

}
